home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9328 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  45 lines

  1. Path: drivel.ics.uci.edu!ucivax!gateway
  2. From: mheiberg@ahi.ICS.UCI.EDU (Michael Heiberg)
  3. Subject: Copy constructor optimization..
  4. Message-ID: <9602291637.aa17139@paris.ics.uci.edu>
  5. Date: 1 Mar 96 00:42:29 GMT
  6. Newsgroups: comp.lang.c++
  7.  
  8.   When constructing a variable from the return value of a function that
  9. returns a copy of that same type, the copy constructor will be called,
  10. but should the return statement copy the answer into the return space,
  11. and then copy that into the object being constructed, or should the
  12. return value be copy-constructed directly into the being-constructed
  13. object?  For example:
  14.  
  15.   #include <iostream.h>
  16.  
  17.   class Vector {
  18.     public:
  19.       Vector() { cout << "Ctor "; }
  20.       Vector(Vector& v) { cout << "Copy "; }
  21.   };
  22.  
  23.   Vector foo(Vector &v) { return v; }    // calls the copy-ctor
  24.  
  25.   main() {
  26.     Vector a;        // ctor
  27.     Vector b=foo(a);    // copy-ctor
  28.   }
  29.  
  30. Output:
  31.   Ctor Copy
  32.  
  33. Function foo returns a Vector by copy, calling the copy constructor, but
  34. Vector b needs to be constructed with that return value.  I have tried
  35. this out on a Gnu, Borland, and Microsoft compiler, with optimizations
  36. turned off, and they all do this operation in one step, producing the
  37. output listed above.  Is this just a very common and trivial optimization,
  38. or does the language actually specify that the constructed object is
  39. copy-constructed with v of foo?
  40.  
  41.   Any thoughts, answers, or references to relevant sections of one of
  42. Stroustrup's books would be appreciated.  Reply by email please.
  43.  
  44. Michael Heiberg - mheiberg@ics.uci.edu - http://www.ics.uci.edu/~mheiberg
  45.